package com.junxonline.plat.service.device.impl;

import com.junxonline.common.dao.pojo.JsTree;
import com.junxonline.common.util.CommonUtils;
import com.junxonline.plat.dao.model.DeviceCheck;
import com.junxonline.plat.dao.model.Menu;
import com.junxonline.plat.dao.model.Device;
import com.junxonline.plat.dao.model.User;
import com.junxonline.plat.dao.repository.DeviceCheckRepository;
import com.junxonline.plat.dao.repository.MenuRepository;
import com.junxonline.plat.dao.repository.DeviceRepository;
import com.junxonline.plat.dao.repository.UserRepository;
import com.junxonline.plat.dao.vo.HouseholdVO;
import com.junxonline.plat.dao.vo.PageVO;
import com.junxonline.plat.dao.vo.QueryDeviceVO;
import com.junxonline.plat.dao.vo.DeviceVO;
import com.junxonline.plat.service.device.DeviceService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DeviceServiceImpl implements DeviceService {

    private Logger logger = LogManager.getLogger();

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private DeviceCheckRepository deviceCheckRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 获取设备数据
     *
     * @param vo
     * @return
     */
    @Override
    public DeviceVO getDevice(QueryDeviceVO vo) {

        Device device = deviceRepository.findByDeviceId(vo.getDeviceId());

        DeviceVO deviceVO = new DeviceVO();
        deviceVO.setDeviceId(device.getDeviceId());
        deviceVO.setDeviceName(device.getDeviceName());
        deviceVO.setDeviceNo(device.getDeviceNo());
        deviceVO.setDevicePrice(device.getDevicePrice());
        deviceVO.setDeviceManufacturer(device.getDeviceManufacturer());
        deviceVO.setDeviceStartTime(device.getDeviceStartTime());
        deviceVO.setDeviceStatus(device.getDeviceStatus());

        User createUser = device.getCreateUser();
        if (CommonUtils.isNotEmpty(createUser)) {
            deviceVO.setCreateUserId(createUser.getUserId());
            deviceVO.setCreateUserName(createUser.getUsername());
        }

        User repairUser = device.getRepairUser();
        if (CommonUtils.isNotEmpty(repairUser)) {
            deviceVO.setRepairUserId(repairUser.getUserId());
            deviceVO.setRepairUserName(repairUser.getUsername());
        }

        return deviceVO;
    }

    /**
     * 筛选查询设备
     *
     * @param pageVO
     * @param vo
     * @return
     */
    @Override
    public PageVO queryDevice(PageVO pageVO, QueryDeviceVO vo) {

        PageRequest pageRequest = PageRequest.of(pageVO.getPage() - 1, pageVO.getLimit(), new Sort(Sort.Direction.ASC, "deviceId"));

        Page<Device> page = deviceRepository.findAll(new Specification<Device>() {
            @Override
            public Predicate toPredicate(Root<Device> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> params = new ArrayList<>();
                String deviceNo = vo.getDeviceNo();
                String deviceName = vo.getDeviceName();

                if (CommonUtils.isNotEmpty(deviceNo)) {
                    params.add(criteriaBuilder.like(root.get("deviceNo"), "%" + deviceNo + "%"));
                }

                if (CommonUtils.isNotEmpty(deviceName)) {
                    params.add(criteriaBuilder.like(root.get("deviceName"), "%" + deviceName + "%"));
                }

                return criteriaBuilder.and(params.toArray(new Predicate[params.size()]));
            }
        }, pageRequest);

        List<DeviceVO> deviceVOs = new ArrayList<>();
        List<Device> devices = page.getContent();

        for (Device device : devices) {

            // 替换设备状态
            switch (device.getDeviceStatus()) {
                case 0:
                    device.setDeviceStatusString("<span class=\"layui-badge layui-bg-green\">启用</span>");
                    break;
                case 1:
                    device.setDeviceStatusString("<span class=\"layui-badge\">禁用</span>");
                    break;
                default:
                    break;
            }

            DeviceVO deviceVO = new DeviceVO();
            deviceVO.setDeviceId(device.getDeviceId());
            deviceVO.setDeviceName(device.getDeviceName());
            deviceVO.setDeviceNo(device.getDeviceNo());
            deviceVO.setDevicePrice(device.getDevicePrice());
            deviceVO.setDeviceManufacturer(device.getDeviceManufacturer());
            deviceVO.setDeviceStartTime(device.getDeviceStartTime());
            deviceVO.setDeviceStatus(device.getDeviceStatus());
            deviceVO.setDeviceStatusString(device.getDeviceStatusString());

            User createUser = device.getCreateUser();
            if (CommonUtils.isNotEmpty(createUser)) {
                deviceVO.setCreateUserId(createUser.getUserId());
                deviceVO.setCreateUserName(createUser.getUsername());
            }

            User repairUser = device.getRepairUser();
            if (CommonUtils.isNotEmpty(repairUser)) {
                deviceVO.setRepairUserId(repairUser.getUserId());
                deviceVO.setRepairUserName(repairUser.getUsername());
            }

            deviceVOs.add(deviceVO);

        }

        pageVO.setTotal(page.getTotalElements());
        pageVO.setData(deviceVOs);

        return pageVO;

    }

    /**
     * 添加设备
     *
     * @param vo
     * @param userId
     * @return
     */
    @Override
    public boolean addDevice(DeviceVO vo, Long userId) {

        Device device = new Device();
        device.setDeviceId(vo.getDeviceId());
        device.setDeviceNo(vo.getDeviceNo());
        device.setDeviceName(vo.getDeviceName());
        device.setDeviceManufacturer(vo.getDeviceManufacturer());
        device.setDevicePrice(vo.getDevicePrice());
        device.setDeviceStartTime(new Date());

        User user = userRepository.findByUserId(userId);

        if (CommonUtils.isNotEmpty(user)) {
            device.setCreateUser(user);
        }

        device.setDeviceStatus(vo.getDeviceStatus());

        deviceRepository.save(device);

        return true;
    }

    /**
     * 修改设备
     *
     * @param vo
     * @return
     */
    @Override
    public boolean editDevice(DeviceVO vo) {

        Device device = deviceRepository.findByDeviceId(vo.getDeviceId());

        device.setDeviceNo(vo.getDeviceNo());
        device.setDeviceName(vo.getDeviceName());
        device.setDeviceManufacturer(vo.getDeviceManufacturer());
        device.setDevicePrice(vo.getDevicePrice());
        device.setDeviceStatus(vo.getDeviceStatus());

        deviceRepository.save(device);

        return true;
    }

    /**
     * 删除设备
     *
     * @param deviceIds
     * @return
     */
    @Override
    public boolean delDevice(Long[] deviceIds) {

        List<Device> devices = deviceRepository.findByDeviceIdIn(deviceIds);

        for (Device device : devices) {
            // 删除设备
            deviceRepository.delete(device);
        }


        return true;
    }

    /**
     * 检修设备
     *
     * @param vo
     * @param userId
     * @return
     */
    @Override
    public boolean addCheckDevice(DeviceVO vo, Long userId) {

        Device device = deviceRepository.findByDeviceId(vo.getDeviceId());

        DeviceCheck deviceCheck = new DeviceCheck();
        deviceCheck.setDeviceCheckStatus(vo.getDeviceCheckStatus());
        deviceCheck.setDeviceCheckDetail(vo.getDeviceCheckDetail());
        deviceCheck.setDeviceId(device.getDeviceId());
        deviceCheck.setDeviceName(device.getDeviceName());
        deviceCheck.setDeviceNo(device.getDeviceNo());

        Date currentTime = new Date();
        deviceCheck.setDeviceCheckTime(currentTime);

        User createUser = device.getCreateUser();
        if (CommonUtils.isNotEmpty(createUser)) {
            deviceCheck.setCreateUser(createUser);
        }

        User user = userRepository.findByUserId(userId);

        if (CommonUtils.isNotEmpty(user)) {
            device.setRepairUser(user);
            deviceCheck.setRepairUser(user);
        }

        deviceRepository.save(device);
        deviceCheckRepository.save(deviceCheck);

        return true;
    }
}
